package guestbook;

import java.io.IOException;
import java.util.logging.Logger;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;

import data.Book;

@SuppressWarnings("serial")
public class AddBookServlet extends HttpServlet {
	private static final Logger s_log = Logger.getLogger(AddBookServlet.class.getName());
	
	public void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {

		String strBookStore = req.getParameter("bookStore");
		Book book = null;
		
		try
		{
			book = new Book(req.getParameter("content"));
		}
		catch (IllegalArgumentException e)
		{
			s_log.warning("cannot parse content: " + e.getMessage());
			resp.sendRedirect("/bookstore.jsp?bookStore=" + strBookStore);
			return;
		}

		s_log.info("Book info:" + book + " is parsed successfully");
		
		Key keyBookStore = KeyFactory.createKey("BookStore", strBookStore);		
		Entity entBook = book.GetEntity(keyBookStore);
		
		DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
		datastore.put(entBook);

		resp.sendRedirect("/bookstore.jsp?bookStore=" + strBookStore);
	}
}
